<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-button type="primary" @click="handleNewtask()">新建任务</el-button>
        <el-button type="primary" @click="handDelete()">删除任务</el-button>
        <el-input v-model="input" placeholder="请输入内容" class="search"><el-button slot="append" icon="el-icon-search"></el-button></el-input>
      </el-col>
    </el-row>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="40"
        align="center"/>
      <el-table-column label="序号" width="50" prop="Id" align="center" />
      <el-table-column label="名称" prop="Name" align="center" />
      <el-table-column label="数据集来源" prop="From" align="center"></el-table-column>
      <el-table-column label="数据集类别" prop="Class" align="center"></el-table-column>
      <el-table-column label="算法模型" prop="VersionName" align="center" />
      <el-table-column label="Crontab" prop="Cron" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.Status | statusFilter">
            <i :class="row.Status | statusIconFilter" />
            {{ row.Status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="text" size="mini" @click="handleChangeStatus(row)">{{ row.Status === 0? '启用':'停用' }}</el-button>
          <el-button type="text" size="mini" @click="handleUpdateCronTask(row)">修改</el-button>
          <el-button type="text" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <pagination v-show="total>0" :total="total" :page.sync="cronQuery.Page" :limit.sync="cronQuery.Size" style="text-align:right" @pagination="getList" />
    </el-row>

    <el-dialog :title="isCreate? '新增任务':'修改任务'" :visible.sync="dialogNewtask" width="60%">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="类别">
          <el-select
            v-model="temp.Class"
            class="filter-item"
            placeholder="请选择"
            style="width: 300px;"
          >
            <el-option v-for="item in classArray" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源">
          <el-select
            v-model="temp.From"
            class="filter-item"
            placeholder="请选择"
            style="width: 300px;"
          >
            <el-option v-for="item in fromArray" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="SDK版本" prop="Version">
          <el-select
            v-model="temp.Version"
            class="filter-item"
            multiple
            placeholder="请选择"
            style="width: 300px; overflow:hidden"
          >
            <el-option
              v-for="item of editionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="crontab" prop="CronStr">
          <input-cron v-model="temp.CronStr" :hide-year="false" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNewtask = false">取消</el-button>
        <el-button type="primary" @click="isCreate? createData() : updateData()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchGetCronTaskList, fetchVersionList, CreateCronTask, DeleteCronTask, ChangeCronTaskStatus, fetchGetDataSetList, UpdateCronTask, DataSetClassAndFrom } from '@/api/video'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import InputCron from '@/components/CronInput/input-cron'

export default {
  name: 'Cron',
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': 'danger',
        '1': 'success',
        '-1': 'danger'
      }
      return statusMap[status]
    },
    statusIconFilter(status) {
      const statusMap = {
        '1': 'el-icon-check',
        '0': 'el-icon-close',
        '-1': 'el-icon-close'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        '1': '启用',
        '0': '停用',
        '-1': '已删除'
      }
      return statusMap[status]
    },
    formatTypeFilter(status) {
      const statusMap = {
        '0': '视频类型',
        '1': '图片类型',
        '2': '文本类型'
      }
      return statusMap[status]
    },
    categoryTypeFilter(status) {
      const statusMap = {
        '-1': '无',
        '0': '低俗审核',
        '1': '内容识别',
        '2': '智能识别',
        '3': '智能推荐',
        '4': '优质挖掘'
      }
      return statusMap[status]
    }
  },
  components: { Pagination, InputCron },
  data() {
    return {
      input: '',
      listLoading: false,
      dialogNewtask: false,
      list: null,
      total: 0,
      multipleSelection: [],
      classArray: [],
      fromArray: [],
      editionOptions: [],
      cronQuery: {
        Page: 1,
        Size: 10
      },
      isCreate: true,
      UpdateRow: '',
      temp: {
        Class: '',
        CronStr: '',
        From: '',
        Type: 0,
        Version: []
      }
    }
  },
  computed: {
    ...mapGetters(['ProjectId']),
    watchProjectId() {
      return this.$store.state.constants.ProjectId
    }
  },
  watch: {
    watchProjectId(curVal, oldVal) {
      this.getList()
    }
  },
  created() {
    this.getList()
    this.DataSetClassAndFrom()
  },
  methods: {
    handleChangeStatus(row) {
      const params = {
        Id: Number(row.Id),
        Status: Number(row.Status) === 0 ? 1 : 0
      }
      ChangeCronTaskStatus(params).then(response => {
        if (response.code === 200) {
          this.getList()
        }
      })
    },
    async handleUpdateCronTask(row) {
      this.temp = {
        CronStr: row.Cron,
        Version: row.Version.map(item => Number(item.VersionId)),
        Class: row.Class,
        From: row.From
      }
      this.UpdateRow = row
      this.isCreate = false
      this.dialogNewtask = true
      await this.fetchVersionList()
    },
    fetchVersionList() {
      const params = {
        ProjectId: -1,
        SdkId: -1
      }
      return new Promise(resolve => {
        fetchVersionList(params).then(response => {
          const editionOptions = []
          response.Data.map(item => {
            if (item.Status === 0) {
              editionOptions.push({
                value: item.VersionId,
                label: item.SdkName.trim().concat('_', item.Version)
              })
            }
          })
          this.editionOptions = editionOptions
          resolve()
        })
      })
    },
    DataSetClassAndFrom() {
      DataSetClassAndFrom().then(response => {
        this.classArray = response.Data[0].Class
        this.fromArray = response.Data[0].From
      })
    },
    handleNewtask() {
      this.dialogNewtask = true
      this.isCreate = true
      this.temp = {
        Class: '',
        CronStr: '',
        From: '',
        Type: 0,
        Version: []
      }
      this.$nextTick(() => {
        this.fetchVersionList()
      })
    },
    createData() {
      const params = {
        ...this.temp,
        ProjectID: Number(this.ProjectId)
      }
      params.Version = params.Version.map(item => {
        const itemObj = {}
        this.editionOptions.forEach(ieach => {
          if (item === Number(ieach.value)) {
            itemObj.VersionId = String(ieach.value)
          }
        })
        return itemObj
      })
      params.Type = Number(params.Type)
      CreateCronTask(params).then(response => {
        this.$refs.dataForm.resetFields()
        this.dialogNewtask = false
        this.getList()
      })
      this.dialogNewtask = false
    },
    updateData() {
      const params = {
        ...this.temp,
        Id: this.UpdateRow.Id,
        Name: this.UpdateRow.Name
      }
      params.Version = params.Version.map(item => {
        const itemObj = {}
        this.editionOptions.forEach(ieach => {
          if (item === Number(ieach.value)) {
            itemObj.VersionId = String(ieach.value)
            itemObj.VersionName = ieach.label
          }
        })
        return itemObj
      })
      UpdateCronTask(params).then(response => {
        this.dialogNewtask = false
        this.getList()
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      if (!this.ProjectId) return
      this.listLoading = true
      const params = {
        ...this.cronQuery,
        ProjectId: this.ProjectId
      }
      fetchGetCronTaskList(params)
        .then(async response => {
          this.list = response.Data.map(item => {
            item.VersionName = item.Version.map(imap => imap.VersionName)
            item.VersionName = item.VersionName.join()
            return item
          })
          this.total = response.Count

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handDelete(){
      this.$alert('确认删除',{  
            cancelButtonText:"取消",
            confirmButtonText:'确认',
            iconClass:"el-icon-success",
            center:true

        }).catch(()=>{
          this.$alert("取消删除")
        })
    }
  }
}
</script>

<style lang="scss" scoped>
  .app {
    &-container {
      margin: 30px;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
  .search {
    width: 30%;
    float: right;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
<style lang="scss" scoped>
  .small-select{
    border-color: #ccc;
    color: #666;
    padding: 0 5px;
  }
  .small-buttom{
    width:100%;
    text-align: left;
    padding: 10px 15px;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    &:active {
      border-color: #c7c9cf;
    }
    &:focus {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    &:hover {
      border-color: #c7c9cf;
      background-color: #fff;
    }
  }
  .small-dropdown{
    width:100%;
    text-align: left;
    padding: 5px 20px 5px 0;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    white-space: normal;
    min-height: 28px;
    &:active {
      border-color: #c7c9cf;
    }
    &:focus {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    &:hover {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    .dropdown-checked{
      display: inline-block;
      font-size: 12px;
      border: 1px solid #e9e9eb;
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      color: #909399;
      padding: 2px 4px 2px 8px;
      border-radius: 3px;
      height: 24px;
      line-height: 18px;
      margin: 2px 0 2px 6px;
    }
    .dropdown-checked_no{
      color:#bbb;
      // margin: 5px 0 5px 12px;
      padding: 0;
      border:none;
      background: none;
      line-height: 22px;
      margin-left: 10px;
    }
    .delete-dataset{
      background-color: #C0C4CC;
      color: #909399;
      border-radius: 50%;
      font-size: 10px;
      padding: 3px 2px 2px 3px;
      margin-left: 5px;
      transform: scale(0.8);
      &:hover{
        background-color: #909399;
        color: #eee;
      }
    }
  }
  >>> .small-dropdown>span{
    display:block;
    word-break:break-all;
    word-wrap:break-word;
    white-space: normal;
  }
  .small-dropdown_active_icon{
    transform: scale(0);
  }
  .small-dropdown_active{
    // background-color: #e8f4ff;
    color: #46a6ff;
    font-weight: bold;
    .small-dropdown_active_icon{
      transform: scale(1);
    }
  }
  .small-dropdown_item{
    padding: 0px 20px;
    &:hover{
      cursor: pointer;
      background-color: #eee;
    }
  }
</style>

